﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Travel.CommonUtil.Snowflake;
using Travel.Data;
using Travel.Data.Dtos;
using Travel.Data.Dtos.TravelBusiness;
using Travel.Data.Entity;
using Travel.Data.Inputs;

namespace Travel.Service.TravelBusiness.Impl
{
    public class FavoriteService : ServiceBase, IFavoriteService
    {

        /// <summary>
        /// 添加收藏夹
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<int>> AddFavorite(AddFavoriteInput input)
        {
            var count = TravelContext.TabFavorites.Count(c => !c.Deleted && c.CreatedUserId == input.LoginUserId && c.TravelId == input.TravelId);
            if (count > 0)
            {
                return Results<int>.FailResult("请不要重复收藏");
            }
            TabFavorite tabFavorite = new TabFavorite()
            {

                CreatedUserId = input.LoginUserId,
                TravelId = input.TravelId,
                UpdatedUserId = input.LoginUserId,
                Id = SnowIdWorker.NextId()
            };
            var tabTravel = TravelContext.TabTravels.FirstOrDefault(c => c.Id == input.TravelId);
            TravelContext.TabFavorites.Add(tabFavorite);
            int row = 0;
            bool save = true;
            while (save)
            {
                try
                {
                    row = await TravelContext.SaveChangesAsync();
                    save = false;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    foreach (var item in ex.Entries)
                    {
                        if (item.Entity is TabTravel)
                        {
                            var databaseValues = item.GetDatabaseValues();
                            var currentValues = item.CurrentValues;
                            foreach (var property in currentValues.Properties)
                            {
                                if (property.Name == nameof(tabTravel.FavoriteCount))
                                {
                                    var databaseValue = databaseValues[property];
                                    currentValues[property] = Convert.ToInt32(databaseValues[property]) + 1;
                                }
                            }
                            //刷新原始的值
                            item.OriginalValues.SetValues(databaseValues);
                        }
                    }
                }

            }

            return Results<int>.DataResult(row);
        }
        /// <summary>
        /// 移除收藏夹
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<int>> RemoveFavorite(long id)
        {
            var tabFavorite = await TravelContext.TabFavorites.FirstOrDefaultAsync(c => c.Id == id && !c.Deleted);
            if (tabFavorite == null)
            {

                return Results<int>.FailResult("数据不存在");
            }
            tabFavorite.Deleted = true;
            var travel = await TravelContext.TabTravels.FindAsync(tabFavorite.TravelId);
            travel.FavoriteCount--;
            var row = 0;
            var save = true;
            while (save)
            {
                try
                {
                    row = await TravelContext.SaveChangesAsync();
                    save = false;

                }
                catch (DbUpdateConcurrencyException ex)
                {
                    foreach (var item in ex.Entries)
                    {
                        if (item.Entity is TabTravel)
                        {
                            var databaseValues = await item.GetDatabaseValuesAsync();
                            var currentValues = item.CurrentValues;
                            foreach (var property in currentValues.Properties)
                            {
                                if (property.Name == nameof(travel.FavoriteCount))
                                {
                                    currentValues[property] = Convert.ToInt32(databaseValues[property]) - 1;
                                }
                            }
                        }
                    }
                }
            }
            return Results<int>.DataResult(row);
        }

        /// <summary>
        /// 查看收藏夹
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<PageDto<FavoriteDto>>> UpdateFavorite(FavoriteQueryInput input)
        {
            var tabFavorites = TravelContext.TabFavorites.AsNoTracking().Include(c => c.Travel).ThenInclude(c => c.Category).Where(c => !c.Deleted && c.CreatedUserId == LoginUserId);
            PageDto<FavoriteDto> page = new PageDto<FavoriteDto>() { Total = tabFavorites.Count() };

            tabFavorites.OrderByDescending(c => c.CreatedTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize);
            var dtoList = tabFavorites.Select(c => new FavoriteDto
            {
                Id = c.Id,
                TravelId = c.TravelId,
                CategoryName = c.Travel.Category.CategoryName,
                Price = c.Travel.Price,
                CreatedTime = c.CreatedTime.Value,
                TravelName = c.Travel.TravelName,
            }).ToList();
            page.Data = dtoList;
            return Results<PageDto<FavoriteDto>>.DataResult(page);
        }
    }
}
